package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.Resource;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.LoginMapper;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.SecurityConfigProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {/*设置该用户是否有增删改查功能(可以设置没有)*/
    @Autowired
    LoginMapper loginMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ResourceMapper resourceMapper;
    @Autowired
    StringRedisTemplate redisTemplate;/*缓存,记得导依赖*/

    @Autowired
    JwtTokenManagerProperties jwtTokenManagerProperties;/*令牌,里面有密钥和过期时间*/
    @Autowired
    SecurityConfigProperties securityConfigProperties;/*这是公共资源和忽略资源*/
    @Override
    public UserVo login(LoginDto loginDto) {
        //1.查询用户
        User user = userMapper.selectByName(loginDto.getUsername());
        //2.判断是否存在
        if(ObjectUtil.isEmpty(user)){
            throw new BaseException(BasicEnum.LOGIN_FAIL);/*不存在抛异常*/
        }
        //3.是否被禁用
        if(user.getDataState().equals(SuperConstant.DATA_STATE_1)){/*就相当于0*/
            throw new BaseException(BasicEnum.ACCOUNT_DISABLED);
        }
        //4.判断密码是否正确,需要解密
        if(!BCrypt.checkpw(loginDto.getPassword(),user.getPassword())){/*方法前面是明文,后面是密文*/
            throw new BaseException(BasicEnum.PASSWORD_ERROR);
        }
        //5.密码脱敏,就是空字符串
        UserVo userVo = BeanUtil.toBean(user, UserVo.class);
        userVo.setPassword("");

        //6.获取用户资源列表(用户个人有哪些资源)
        List<Resource> resourceList = resourceMapper.selectResourceList(user.getId());
        //取出request_path
        List<String> urlList = resourceList.stream().map(resource -> resource.getRequestPath()).collect(Collectors.toList());
        //7.获取白名单url列表(公共资源)
        List<String> publicAccessUrls = securityConfigProperties.getPublicAccessUrls();
        urlList.addAll(publicAccessUrls);/*合二为一,就是用户的所有资源*/


        //8.根据用户生成jwt令牌
        Map<String,Object> claims = new HashMap();
        claims.put("currentUser", JSONUtil.toJsonStr(userVo));/*这里怎么存的到时候怎么取!*/
        String jwt = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                jwtTokenManagerProperties.getTtl(),
                claims);
        //过期时间
        int ttl = jwtTokenManagerProperties.getTtl() / 1000;

        //9.存储到Redis(key:用户id;value:可访问的url列表)
        redisTemplate.opsForValue().set(
                user.getId().toString(),
                JSONUtil.toJsonStr(urlList),
                ttl,
                TimeUnit.SECONDS);

        //设置token
        userVo.setUserToken(jwt);
        return userVo;
    }
}
